package com.cabinet.ui;

import com.cabinet.Config;
import com.cabinet.Device;
import com.cabinet.db.DBDeviceState;

import javax.activation.DataHandler;
import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: lesya
 * Date: 11/24/13
 * Time: 12:49 PM
 * To change this template use File | Settings | File Templates.
 */
public abstract class ClassPanelWithBottomConferences extends ClassPanel {
  final int H = 65;

  void showbottomConferences(Map<Long,DBDeviceState> dbDevices){
    Map<Long,java.util.List<DBDeviceState>> byConfer = groupByConference(dbDevices.values());

    bottomConferences.removeAll();
    bottomConferences.repaint();
    for( int i=-1; i<10; i++ ){
      String kBg = "K/K0" + (i+1) + ".png";

      int padSize = 25;
      if( i==-1 ){
        kBg = "K/Kof.png";
        padSize=35;
      }
      if( i==8 ){
        kBg = "K/Kvc.png";
        padSize=45;
      }
      if( i==9 ){
        kBg = "K/Kst.png";
        padSize=0;
      }
      addBottomConference(byConfer, i, kBg);

      if( padSize>0 ){
        JLabel pad = new JLabel("");
        pad.setBorder(BorderFactory.createEmptyBorder(1,padSize,1,1));
        bottomConferences.add(pad);
      }
    }
    bottomConferences.doLayout();
  }

  private void addBottomConference(Map<Long, java.util.List<DBDeviceState>> byConfer, int i, String kBg) {
    final int conf = i;

    java.util.List<DBDeviceState> dbDeviceStates = byConfer.get((long) i);
    if( i==-1 ){
      dbDeviceStates=null; // don't show OFFLINE (not on a conference) devices
    }
    boolean hasStudentOnConf = false;
    if( dbDeviceStates !=null ){
      Collections.sort(dbDeviceStates, cmpConferenceDevs);
      for(DBDeviceState st : dbDeviceStates){
        JLabel labelBackground;
        if( st.getDevId()== Device.TEACHER ){
          String file = "T_K_tl.png";
          if( st.isListen() && st.isSpeak() ){
            file = "T_K_ol.png";
          }else if( st.isSpeak() ){
            file = "T_K_mk.png";
          }
          ImageIcon icon = new ImageIcon(Config.getScaledImage("Kicon/" + file, 0, H));
          labelBackground = new JLabel(icon);
          bottomConferences.add(labelBackground);
        }else if( Device.isAudioDevice(st.getDevId()) ){
          String ic = "A0"+Device.audioDevNumber(st.getDevId());
          if( st.isListen() ){
            ic += "_re.png";
          }else if( st.isSpeak() ){
            ic += "_pl.png";
          } else {
            ic += "_of.png";
          }
          ImageIcon icon = new ImageIcon(Config.getScaledImage("Kicon/"+ic, 0, H));
          labelBackground = new JLabel(icon);
          bottomConferences.add(labelBackground);
        }else{
          hasStudentOnConf = true;
          JPanel p = new JPanel(null);
          ImageIcon iconBg = new ImageIcon(Config.getScaledImage(kBg, 0, H));

          String s = ""+(st.getDevId()+1);
          if( s.length()==1 ){
            s = "0" + s;
          }
          ImageIcon iconStudNum = new ImageIcon(Config.getScaledImage("Kicon/Yk" + s + ".png", 0, H /5));
          JLabel lNum = new JLabel(iconStudNum);
          p.add(lNum);
          lNum.setLocation( (iconBg.getIconWidth()-iconStudNum.getIconWidth())/2, 3);
          lNum.setSize(iconStudNum.getIconWidth(), iconStudNum.getIconHeight());

          if( st.isListen() ){
            ImageIcon iconTLF = new ImageIcon(Config.getScaledImage("Kicon/MKF.png", 0, H /5));
            JLabel lTLF = new JLabel(iconTLF);
            p.add(lTLF);
            lTLF.setLocation((iconBg.getIconWidth()-iconTLF.getIconWidth())/2, H /3);
            lTLF.setSize(iconTLF.getIconWidth(), iconTLF.getIconHeight());
          }

          if( st.isSpeak() ){
            ImageIcon iconMKF = new ImageIcon(Config.getScaledImage("Kicon/TLF.png", 0, H /5));
            JLabel lMKF = new JLabel(iconMKF);
            p.add(lMKF);
            lMKF.setLocation((iconBg.getIconWidth()-iconMKF.getIconWidth())/2, 2* H /3);
            lMKF.setSize(iconMKF.getIconWidth(), iconMKF.getIconHeight());
          }

          labelBackground = new JLabel(iconBg);
          p.setPreferredSize(new Dimension(iconBg.getIconWidth(), iconBg.getIconHeight()));
          labelBackground.setLocation(0, 0);
          labelBackground.setSize(p.getPreferredSize());
          p.add(labelBackground);
          bottomConferences.add(p);
        }

        BottomTransferHandler transferHandler = new BottomTransferHandler(conf);
        transferHandler.devId = st.getDevId();
        labelBackground.setTransferHandler(transferHandler);

        MouseListener ml = new MouseAdapter(){
          public void mousePressed(MouseEvent e){
            if( e.getButton() == MouseEvent.BUTTON1 ){
              JComponent jc = (JComponent)e.getSource();
              TransferHandler th = jc.getTransferHandler();
              th.exportAsDrag(jc, e, TransferHandler.COPY);
            }
          }
        };
        labelBackground.addMouseListener(ml);
        labelBackground.setComponentPopupMenu(devicePanels.get(st.getDevId()).popupMenu);

      }
    }

    if( ! hasStudentOnConf ){
      ImageIcon icon = new ImageIcon(Config.getScaledImage(kBg, 0, H));
      JLabel l = new JLabel(icon);
      BottomTransferHandler transferHandler = new BottomTransferHandler(conf);
      l.setTransferHandler(transferHandler);
      bottomConferences.add(l);
    }
  }

  class BottomTransferHandler extends TransferHandler {
    private final int conf;
    //String deviceName;
    long devId;

    public BottomTransferHandler(int conf) {
      super("text");
      this.conf = conf;
    }

    @Override
    protected Transferable createTransferable(JComponent c) {
      return new DataHandler(new Long[]{devId}, dragDropObjectFlavor.getMimeType());
    }

    @Override
    public boolean canImport(TransferSupport info) {
      try {
        Long[] values = (Long[])info.getTransferable().getTransferData(dragDropObjectFlavor);
        if( conf == CONFERENCE_SELF_TEST ){
          for(int i=0; i<values.length; i++) {
            long devId = values[i];
            if( Device.hasSelfTest(devId) ){
              return true;
            }
          }
          return false; // cannot drag teacher to SelfTest
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      return true;
    }

    @Override
    public boolean importData(TransferSupport info) {
      try {
        Long[] values = (Long[])info.getTransferable().getTransferData(dragDropObjectFlavor);
        if( conf == CONFERENCE_SELF_TEST ){
          for(int i=0; i<values.length; i++) {
            long devId = values[i];
            devicePanels.get(devId).selfTestSet(true);
          }
          return true;
        }

       // JList target = conferenceLists.get((long) conf);
       // DefaultListModel listModel = (DefaultListModel)target.getModel();
        for(int i=0; i<values.length; i++) {
          long devId = values[i];
          if( devicePanels.get(devId).selftest.isSelected() ){
            devicePanels.get(devId).selfTestSet(false);
          }
          devicePanels.get(devId).conferenceId = conf;
//          if( ! listModel.contains(values[i]) ){
//            listModel.addElement(values[i]);
//          }
        }
        //cleanupOtherlistsAfterDragDrop(target, values);
        devicesConfigChanged();

//            Object[] values = (Object[])info.getTransferable().getTransferData(dragDropObjectFlavor);
//            for( Object o : values ){
//              String sname = (String)o;
//              System.out.println("drag "+sname+" to "+conf);
//            }
        return true;
      } catch (Exception e) {
        e.printStackTrace();
      }
      return false;
    }
  }
}
